package com.ly.mp.busicen.rule.instrumentation;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.ly.mp.busicen.rule.XruleStrUtils;
import com.ly.mp.busicen.rule.config.XruleConfig;

/**
 * 
 * @Description: 加载 debug/metrics 的类
 */
public class FlowInstrumentationContainer implements ApplicationListener<ContextRefreshedEvent> {
	
	private static final Logger log = LoggerFactory.getLogger(FlowInstrumentationContainer.class);
	
	private List<IFlowInstrumentation> instrumentationCtn = new LinkedList<IFlowInstrumentation>();

	@Autowired
	XruleConfig xruleConfig;
	
	@Value("${xrule.debug.enable:false}")
	private boolean debugEnable;
	
	@Value("${xrule.metrics.enable:false}")
	private boolean metricsEnable;
	
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		Map<String, IFlowInstrumentation> instruments = event.getApplicationContext().getBeansOfType(IFlowInstrumentation.class);
		log.info("规则引擎加载探测器：【{}】",xruleConfig.xruleInstrumentCfg().labels());
		xruleConfig.xruleInstrumentCfg().labels().forEach(label->{
			if (XruleStrUtils.isEmpty(label)) {
				String errmsg = "规则引擎探测器加载异常，无法加载label为空的探测器";
				throw new RuntimeException(errmsg);
			}
			
			Optional<IFlowInstrumentation> instrumentOpt = instruments.values().stream().filter(m->label.equals(m.label())).findFirst();
			if (instrumentOpt.isPresent()) {
				if (label.equals("debug")) {
					if (debugEnable) {
						instrumentationCtn.add(instrumentOpt.get());
					}
				}else if(label.equals("metrics")){
					if (metricsEnable) {
						instrumentationCtn.add(instrumentOpt.get());
					}
				}else {
					instrumentationCtn.add(instrumentOpt.get());
				}
				
			}else {
				String errmsg = String.format("规则引擎探测器加载异常,不存在label为【%s】的探测器", label);
				throw new RuntimeException(errmsg);
			}
		});
	}
	
	
	public Collection<IFlowInstrumentation> getInstrumentations(){
		return instrumentationCtn;
	}
	

}
